package com.hezhou.hezhouesjd.service;

import com.alibaba.fastjson.JSON;
import com.hezhou.hezhouesjd.pojo.Content;
import com.hezhou.hezhouesjd.utils.HtmlParseUtil;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;

import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * ---------------------------
 * (ContentService) jd信息服务层
 * ---------------------------
 *
 * @Author: [hezhou]
 * @Date: 2020/5/14
 * @Version: [1.0.1]
 * ---------------------------
 */
@Service
public class ContentService {

    @Resource
    private RestHighLevelClient restHighLevelClient;

    /**
     *  1. 解析数据  放入es索引中
     */
    public Boolean parseContent(String keyword) throws IOException {
        List<Content> contents = new HtmlParseUtil().parseJd(keyword);
        //把查询出来的数据放入es中
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2m");
        for (int i= 0;i < contents.size();i++){
            bulkRequest.add(
                    new IndexRequest("jd_good")
                            .source(JSON.toJSONString(contents.get(i)),XContentType.JSON));
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        return !bulk.hasFailures();
    }

    /**
     * 获取数据 实现基本的搜索功能
     */
    public List<Map<String,Object>> searchPage(String keyword,int pageNo,int pageSize) throws IOException {
        if (pageNo<=1){
            pageNo = 1;
        }

        //条件搜索
        SearchRequest searchRequest = new SearchRequest("jd_good");
        //构造搜索器
        SearchSourceBuilder builder = new SearchSourceBuilder();

        //设置高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        //设置不高亮所有高亮
        highlightBuilder.requireFieldMatch(false);
        highlightBuilder.field("title");
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        builder.highlighter(highlightBuilder);

        //设置超时时间
        builder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        //分页功能
        builder.from(pageNo);
        builder.size(pageSize);
        //精准匹配title为传入的title
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keyword);
        builder.query(termQueryBuilder);
        //绑定查询请求
        searchRequest.source(builder);
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        //解析结果
        List<Map<String,Object>> list = new ArrayList<>();
        for (SearchHit hit : search.getHits().getHits()) {
            //解析高亮的字段
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField title = highlightFields.get("title");
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            //替换高亮
            if (title!=null){
                Text[] fragments = title.fragments();
                //将原来的字段换为我们高亮的值字段
                String n_title = "";
                for (Text fragment : fragments) {
                    n_title += fragment;
                }
                //开始替换
                sourceAsMap.put("title",n_title);
            }
            list.add(sourceAsMap);
        }
        return list;
    }
}
